#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" PlurQ, a simple Plurk desktop client using Plurk mobile interface.
    
    Copyright (C) 2010 Ryan Ho <koungho@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2 as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""

#Cookie實作參考自 http://bazaar.launchpad.net/~openobject-client-kde/openobject-client-kde/5.0/annotate/head:/Koo/Common/Common.py

import sys
from mainui import Ui_MainWindow
from about import Ui_Dialog
from account import Acc_Dialog
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtNetwork import QNetworkCookieJar, QNetworkCookie

class CookieJar(QNetworkCookieJar):
    def __init__(self, parent=None):
        QNetworkCookieJar.__init__(self, parent)
        
    def allCookies(self):
        return QNetworkCookieJar.allCookies(self)
    
    def setAllCookies(self, cookielist):
        QNetworkCookieJar.setAllCookies(self, cookielist)

class PlurQ(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.settings = QSettings('RyanHo', 'PlurQ')
        self.restoreGeometry(self.settings.value('geometry').toByteArray())
        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        # 紀錄帳號還未被實作
        self.ui.actionAccount_setting.setDisabled(True)
        
        self._url = QUrl('http://www.plurk.com/m')
            
        self.cookieJar = CookieJar()
        self.ui.webView.page().networkAccessManager().setCookieJar(self.cookieJar)
        self._restoreState()
        self.ui.webView.setUrl(self._url) 
        
        self.connect(self.ui.actionAccount_setting, SIGNAL('triggered()'), self._account)
        self.connect(self.ui.actionAbout, SIGNAL('triggered()'), self._about)
        self.connect(self.ui.actionExit, SIGNAL('triggered()'), self.close)
        
    def _account(self):
        dlg = Accountdlg(self)
        dlg.show()
    
    def _about(self):
        dlg = aboutdialog(self)
        dlg.show()
        
    #在關閉主程式時，儲存視窗位置與cookie
    def closeEvent(self, event):
        self.settings.setValue('geometry', self.saveGeometry())
        self._saveState()
        
    #儲存cookie到QSettings
    def _saveState(self):
        cookieList = self.cookieJar.allCookies()
        raw = []
        for cookie in cookieList:
            if cookie.isSessionCookie():
                continue
            raw.append([
                        str(cookie.name().toBase64()),
                        str(cookie.value().toBase64()),
                        unicode(cookie.path()).encode('utf-8'),
                        unicode(cookie.domain()).encode('utf-8'),
                        unicode(cookie.expirationDate().toString()).encode('utf-8'),
                        str(cookie.isSecure())
                        ])
            self.settings.setValue('cookie', QByteArray(str(raw)))
            
    #載入cookie到QSettings
    def _restoreState(self):
        value = self.settings.value('cookie').toByteArray()
        if not value:
            return
        raw = eval(str(value))
        cookieList = []
        for cookie in raw:
            name = QByteArray.fromBase64( cookie[0] )
            value = QByteArray.fromBase64( cookie[1] )
            networkCookie = QNetworkCookie( name, value )
            networkCookie.setPath( unicode( cookie[2], 'utf-8' ) )
            networkCookie.setDomain( unicode( cookie[3], 'utf-8' ) )
            networkCookie.setExpirationDate( QDateTime.fromString( unicode( cookie[4], 'utf-8' ) ) )
            networkCookie.setSecure( eval(cookie[5]) )
            cookieList.append( networkCookie )
        self.cookieJar.setAllCookies(cookieList)
        self.ui.webView.page().networkAccessManager().setCookieJar(self.cookieJar)
            
class Accountdlg(QDialog):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        dlg = Acc_Dialog()
        dlg.setupUi(self)
        
class aboutdialog(QDialog):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        dlg = Ui_Dialog()
        dlg.setupUi(self)
        
        self.connect(dlg.pushButton, SIGNAL('clicked()'), self.close)
                
if __name__ == '__main__':
    app = QApplication(sys.argv)
    myapp = PlurQ()
    myapp.show()
    sys.exit(app.exec_())